package com.imooc.order.message;

import com.fasterxml.jackson.core.type.TypeReference;
import com.imooc.order.util.JsonUtil;
import com.imooc.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 接收商品服务的扣库存消息
 * @author steve
 * @date 2020/6/23 4:09 上午
 */
@Component
@Slf4j
public class ProductInfoReceiver {
    public static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";
    
    @Autowired
    private StringRedisTemplate template;

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void ProductInfoMessage(String message) {
        //接收到的消息进行转换 message -> productInfoOutputList,并打印
        List<ProductInfoOutput> productInfoOutputList = (List<ProductInfoOutput>) JsonUtil.fromJson(message,
                new TypeReference<List<ProductInfoOutput>>() {});
        log.info("从【{}】队列接收到消息：{}", "productInfo", productInfoOutputList);

        //遍历集合
        for (ProductInfoOutput productInfoOutput : productInfoOutputList) {
            //接收到商品减库存的消息后，把消息数据存入到redis中,key是ProductId，value是ProductStock
            template.opsForValue().set(String.format(PRODUCT_STOCK_TEMPLATE, productInfoOutput.getProductId()),
                    String.valueOf(productInfoOutput.getProductStock()));
        }
    }
}
